'use client';

import React, { useEffect, useState } from 'react';
import { Layout } from '@/components/layout';
import { useApp } from '@/hooks';
import { detectTimeConflicts, getScheduleStats } from '@/lib/conflicts';
import { Conflict, ScheduleItem } from '@/types';
import Link from 'next/link';

const SchedulePage: React.FC = () => {
  const { state } = useApp();
  const [conflicts, setConflicts] = useState<Conflict[]>([]);
  const [viewMode, setViewMode] = useState<'timeline' | 'list'>('timeline');

  useEffect(() => {
    if (!state.userSchedule) {
      return;
    }

    // 检测冲突
    const detectedConflicts = detectTimeConflicts(state.userSchedule.items);
    setConflicts(detectedConflicts);
  }, [state.userSchedule]);

  if (!state.userSchedule || state.userSchedule.items.length === 0) {
    return (
      <Layout>
        <div className="container mx-auto px-4 py-20 text-center">
          <div className="text-6xl mb-4">📅</div>
          <h2 className="text-2xl font-bold text-foreground mb-4">您还没有添加任何日程</h2>
          <p className="text-muted mb-8">
            请先通过推荐页面选择您感兴趣的会议，或者直接浏览所有可用的会议
          </p>
          <div className="space-x-4">
            <Link href="/recommendations" className="btn btn-primary px-8 py-3">
              获取推荐日程
            </Link>
            <Link href="/profile" className="btn btn-secondary px-8 py-3">
              重新构建画像
            </Link>
          </div>
        </div>
      </Layout>
    );
  }

  const stats = getScheduleStats(state.userSchedule.items);
  const sortedItems = [...state.userSchedule.items].sort(
    (a, b) => a.agendaItem.startTime.getTime() - b.agendaItem.startTime.getTime()
  );

  // 按日期分组
  const itemsByDate = sortedItems.reduce((acc, item) => {
    const date = item.agendaItem.startTime.toDateString();
    if (!acc[date]) acc[date] = [];
    acc[date].push(item);
    return acc;
  }, {} as Record<string, ScheduleItem[]>);

  const formatTime = (date: Date) => {
    return date.toLocaleString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    });
  };

  const getConflictLevel = (itemId: string) => {
    const itemConflicts = conflicts.filter(c => 
      c.items.some(item => item.id === itemId)
    );
    
    if (itemConflicts.some(c => c.severity === 'critical')) return 'critical';
    if (itemConflicts.some(c => c.severity === 'high')) return 'high';
    if (itemConflicts.some(c => c.severity === 'medium')) return 'medium';
    return 'none';
  };

  const getConflictColor = (level: string) => {
    switch (level) {
      case 'critical': return 'border-error bg-error/10';
      case 'high': return 'border-warning bg-warning/10';
      case 'medium': return 'border-warning/60 bg-warning/5';
      default: return 'border-border';
    }
  };

  return (
    <Layout>
      <div className="container mx-auto px-4 py-8">
        {/* 页面标题和统计 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-foreground mb-4">
            📅 我的云栖大会日程
          </h1>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 max-w-4xl mx-auto">
            <div className="bg-surface rounded-lg p-4 border border-border">
              <div className="text-2xl font-bold text-primary">{stats.totalItems}</div>
              <div className="text-sm text-muted">会议场次</div>
            </div>
            <div className="bg-surface rounded-lg p-4 border border-border">
              <div className="text-2xl font-bold text-primary">{stats.totalDurationHours}h</div>
              <div className="text-sm text-muted">总时长</div>
            </div>
            <div className="bg-surface rounded-lg p-4 border border-border">
              <div className="text-2xl font-bold text-primary">{stats.uniqueCategories}</div>
              <div className="text-sm text-muted">会议类型</div>
            </div>
          </div>
        </div>

        {/* 冲突警告 */}
        {conflicts.length > 0 && (
          <div className="bg-error/10 border border-error/20 rounded-lg p-4 mb-8">
            <h3 className="text-lg font-semibold text-error mb-2">
              ⚠️ 检测到 {conflicts.length} 个日程冲突
            </h3>
            <div className="space-y-2">
              {conflicts.slice(0, 3).map((conflict) => (
                <div key={conflict.id} className="text-sm text-error">
                  • {conflict.items.map(item => item.agendaItem.title).join(' 与 ')} 
                  {conflict.type === 'time_overlap' && ' 存在时间重叠'}
                  {conflict.type === 'location_distance' && ' 换场时间不足'}
                  {conflict.type === 'no_break_time' && ' 缺少休息时间'}
                </div>
              ))}
              {conflicts.length > 3 && (
                <div className="text-sm text-muted">
                  还有 {conflicts.length - 3} 个冲突...
                </div>
              )}
            </div>
          </div>
        )}

        {/* 视图切换 */}
        <div className="flex justify-between items-center mb-6">
          <div className="flex space-x-2">
            <button
              onClick={() => setViewMode('timeline')}
              className={`btn ${viewMode === 'timeline' ? 'btn-primary' : 'btn-secondary'}`}
            >
              时间轴视图
            </button>
            <button
              onClick={() => setViewMode('list')}
              className={`btn ${viewMode === 'list' ? 'btn-primary' : 'btn-secondary'}`}
            >
              列表视图
            </button>
          </div>
          
          <Link href="/export" className="btn btn-outline">
            📄 导出日程
          </Link>
        </div>

        {/* 日程内容 */}
        <div className="space-y-8">
          {Object.entries(itemsByDate).map(([dateString, items]) => (
            <div key={dateString}>
              <h2 className="text-xl font-semibold text-foreground mb-4 sticky top-20 bg-background py-2 z-10">
                {formatDate(dateString)}
              </h2>
              
              <div className={viewMode === 'timeline' ? 'space-y-4' : 'grid gap-4'}>
                {items.map((item) => {
                  const conflictLevel = getConflictLevel(item.id);
                  const duration = item.agendaItem.endTime.getTime() - item.agendaItem.startTime.getTime();
                  const durationMinutes = Math.round(duration / (1000 * 60));

                  return (
                    <div
                      key={item.id}
                      className={`
                        card border-2 ${getConflictColor(conflictLevel)}
                        ${viewMode === 'timeline' ? 'ml-16 relative' : ''}
                      `}
                    >
                      {viewMode === 'timeline' && (
                        <div className="absolute -left-16 top-6 text-sm font-medium text-foreground w-12">
                          {formatTime(item.agendaItem.startTime)}
                        </div>
                      )}
                      
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex-1">
                          <h3 className="text-lg font-semibold text-foreground mb-1">
                            {item.agendaItem.title}
                          </h3>
                          <div className="flex items-center space-x-4 text-sm text-muted">
                            {viewMode === 'list' && (
                              <span>📅 {formatTime(item.agendaItem.startTime)} - {formatTime(item.agendaItem.endTime)}</span>
                            )}
                            <span>📍 {item.agendaItem.location}</span>
                            <span>⏱️ {durationMinutes}分钟</span>
                            {item.agendaItem.rating && (
                              <span>⭐ {item.agendaItem.rating}</span>
                            )}
                          </div>
                        </div>
                        
                        {conflictLevel !== 'none' && (
                          <div className="text-error text-xs font-medium px-2 py-1 bg-error/20 rounded">
                            冲突
                          </div>
                        )}
                      </div>

                      <p className="text-sm text-muted mb-4 line-clamp-2">
                        {item.agendaItem.description}
                      </p>

                      <div className="flex items-center justify-between">
                        <div className="flex flex-wrap gap-2">
                          {item.agendaItem.tags.slice(0, 3).map(tag => (
                            <span
                              key={tag}
                              className="bg-primary/10 text-primary px-2 py-1 rounded text-xs"
                            >
                              {tag.replace('_', ' ').toUpperCase()}
                            </span>
                          ))}
                        </div>
                        
                        {item.agendaItem.speakers.length > 0 && (
                          <div className="text-xs text-muted">
                            👤 {item.agendaItem.speakers.map(s => s.name).join(', ')}
                          </div>
                        )}
                      </div>

                      {item.notes && (
                        <div className="mt-3 p-3 bg-primary/5 rounded-lg">
                          <div className="text-xs text-muted mb-1">个人备注:</div>
                          <div className="text-sm text-foreground">{item.notes}</div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        {/* 操作按钮 */}
        <div className="mt-12 text-center space-y-4">
          <div className="flex justify-center space-x-4">
            <Link href="/recommendations" className="btn btn-primary px-6">
              添加更多会议
            </Link>
            <Link href="/export" className="btn btn-outline px-6">
              导出完整日程
            </Link>
          </div>
          <p className="text-sm text-muted">
            提示：如有冲突建议，请返回推荐页面重新选择合适的时间段
          </p>
        </div>
      </div>
    </Layout>
  );
};

export default SchedulePage;